﻿using System;
using SkyR1deR;

namespace Modbus.Request
{
    class reqTCP
    {
        private byte[] reqBytes;
        public byte[] MBAP; //byte 0 to 6 (TransactionId[2],ProtocolId[2],Length[2],UnitId[1])
        public byte[] PDU; //byte 7 to End (FunctionCode[1],Data[...])

        public UInt16 TransactionId;
        public UInt16 ProtocolId;
        public UInt16 Length;
        public UInt16 UnitId;
        public UInt16 FunctionCode;

        public reqTCP(byte[] reqBytes) 
        {
            this.reqBytes = reqBytes;
            this.TransactionId = Tools.bytesToUInt16(reqBytes, 0, false);
            this.ProtocolId = Tools.bytesToUInt16(reqBytes, 2, false);
            this.Length = Tools.bytesToUInt16(reqBytes, 4, true);
            this.UnitId = reqBytes[6];
            this.FunctionCode = reqBytes[7];

            this.MBAP = new byte[7];
            Array.ConstrainedCopy(reqBytes, 0, this.MBAP, 0, 7);
            this.PDU = new byte[reqBytes.Length - 7];
            Array.ConstrainedCopy(reqBytes, 7, this.PDU, 0, reqBytes.Length - 7);            
        }

        public byte[] getBytes()
        {
            return reqBytes;
        }

        public override string ToString()
        {
            String str = "";
            int i = 0;
            while (i <= reqBytes.Length - 1)
            {
                str += reqBytes[i].ToString("X2") + " ";
                i++;
            }
            return str;
        }
    }
}
